package com.java.basis.io.nio.two;

import java.io.IOException;
import java.lang.management.ThreadMXBean;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * 客户端代码实现
 *
 * @author wangning
 * @create 2022-01-11 20:29
 */
public class Client {
	//1.定义相关属性
	private Selector selector;
	private static final int PORT = 9999;
	private SocketChannel socketChannel;

	//2.初始化客户端信息
	public Client() {
		try {
			//创建选择器
			selector = Selector.open();
			//连接服务端
			socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", PORT));
			//设置非阻塞模式
			socketChannel.configureBlocking(false);
			socketChannel.register(selector, SelectionKey.OP_READ);

			//
			System.out.println("当前客户端已经准备完成");


		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Client client = new Client();
		//定义一个线程专门负责监听服务端发送过来的读消息时间
		new Thread(new Runnable() {
			@Override
			public void run() {
				client.readInfo();
			}
		}).start();

		Scanner scanner = new Scanner(System.in);
		while (scanner.hasNextLine()) {
			String s = scanner.nextLine();
			client.sendToServer(s);
		}

	}

	/**
	 *
	 * @param s
	 */
	private void sendToServer(String s) {
		try {
			socketChannel.write(ByteBuffer.wrap(("hhah：" + s).getBytes()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void readInfo() {
		try {
			while (selector.select() > 0) {
				Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
				while (iterator.hasNext()) {
					SelectionKey key = iterator.next();
					if (key.isReadable()) {
						SocketChannel sc = (SocketChannel) key.channel();
						ByteBuffer buffer = ByteBuffer.allocate(1024);
						sc.read(buffer);
						System.out.println(new String(buffer.array()).trim());

					}
					iterator.remove();

				}
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
	}
}
